package com.ruoyi.web.controller.asset;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.asset.domain.TAsset;
import com.ruoyi.asset.domain.AssetStatistics;
import com.ruoyi.asset.domain.dto.AssetDTO;
import com.ruoyi.asset.service.ITAssetService;
import com.ruoyi.asset.util.AssetConverter;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/system/asset")
public class TAssetController extends BaseController
{
    @Autowired
    private ITAssetService tAssetService;

    /**
     * 查询资产列表
     */
    @PreAuthorize("@ss.hasPermi('system:asset:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAsset tAsset)
    {
        startPage();
        List<TAsset> list = tAssetService.selectTAssetList(tAsset);
        // 转换为DTO
        List<AssetDTO> dtoList = AssetConverter.toDTOList(list);
        return getDataTable(dtoList);
    }

    /**
     * 查询资产列表（DTO格式，用于前端下拉选择）
     */
    @GetMapping("/list-dto")
    public AjaxResult listDTO(TAsset tAsset)
    {
        List<TAsset> list = tAssetService.selectTAssetList(tAsset);
        List<AssetDTO> dtoList = AssetConverter.toDTOList(list);
        return success(dtoList);
    }

    /**
     * 导出资产列表
     */
    @PreAuthorize("@ss.hasPermi('system:asset:export')")
    @Log(title = "资产", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TAsset tAsset)
    {
        List<TAsset> list = tAssetService.selectTAssetList(tAsset);
        ExcelUtil<TAsset> util = new ExcelUtil<TAsset>(TAsset.class);
        util.exportExcel(response, list, "资产数据");
    }

    /**
     * 获取资产详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:asset:query')")
    @GetMapping(value = "/{assetNo}")
    public AjaxResult getInfo(@PathVariable("assetNo") String assetNo)
    {
        TAsset asset = tAssetService.selectTAssetByAssetNo(assetNo);
        AssetDTO dto = AssetConverter.toDTO(asset);
        return success(dto);
    }

    /**
     * 新增资产
     */
    @PreAuthorize("@ss.hasPermi('system:asset:add')")
    @Log(title = "资产", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AssetDTO assetDTO)
    {
        TAsset asset = AssetConverter.toEntity(assetDTO);
        return toAjax(tAssetService.insertTAsset(asset));
    }

    /**
     * 修改资产
     */
    @PreAuthorize("@ss.hasPermi('system:asset:edit')")
    @Log(title = "资产", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetDTO assetDTO)
    {
        TAsset asset = AssetConverter.toEntity(assetDTO);
        return toAjax(tAssetService.updateTAsset(asset));
    }

    /**
     * 删除资产
     */
    @PreAuthorize("@ss.hasPermi('system:asset:remove')")
    @Log(title = "资产", businessType = BusinessType.DELETE)
	@DeleteMapping("/{assetNos}")
    public AjaxResult remove(@PathVariable String[] assetNos)
    {
        return toAjax(tAssetService.deleteTAssetByAssetNos(assetNos));
    }

    /**
     * 更新资产状态
     */
    @PreAuthorize("@ss.hasPermi('system:asset:edit')")
    @Log(title = "资产状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody AssetStatusRequest request)
    {
        try {
            // 获取当前资产信息
            TAsset currentAsset = tAssetService.selectTAssetByAssetNo(request.getAssetNo());
            if (currentAsset == null) {
                return error("资产不存在");
            }

            // 验证状态变更是否合理
            String currentStatus = currentAsset.getStatusCode();
            String newStatus = request.getStatusCode();
            
            if (currentStatus != null && currentStatus.equals(newStatus)) {
                return success("状态未发生变化");
            }

            // 验证状态转换的合理性
            if (!isValidStatusTransition(currentStatus, newStatus)) {
                return error("非法的状态转换: " + getStatusName(currentStatus) + " -> " + getStatusName(newStatus));
            }

            // 更新资产状态
            currentAsset.setStatusCode(newStatus);
            int result = tAssetService.updateTAsset(currentAsset);
            
            if (result > 0) {
                return success("状态更新成功: " + getStatusName(currentStatus) + " -> " + getStatusName(newStatus));
            } else {
                return error("状态更新失败");
            }
        } catch (Exception e) {
            return error("状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新资产状态
     */
    @PreAuthorize("@ss.hasPermi('system:asset:edit')")
    @Log(title = "资产状态", businessType = BusinessType.UPDATE)
    @PutMapping("/batchStatus")
    public AjaxResult batchUpdateStatus(@RequestBody BatchAssetStatusRequest request)
    {
        int result = 0;
        for (String assetNo : request.getAssetNos()) {
            TAsset asset = new TAsset();
            asset.setAssetNo(assetNo);
            asset.setStatusCode(request.getStatusCode());
            result += tAssetService.updateTAsset(asset);
        }
        return toAjax(result);
    }

    /**
     * 获取资产维修历史
     */
    @PreAuthorize("@ss.hasPermi('system:asset:query')")
    @GetMapping("/repairHistory")
    public TableDataInfo getRepairHistory(String assetNo, String startDate, String endDate)
    {
        startPage();
        List<TAsset> list = tAssetService.selectAssetRepairHistory(assetNo, startDate, endDate);
        return getDataTable(list);
    }

    /**
     * 获取资产统计信息
     */
    @PreAuthorize("@ss.hasPermi('system:asset:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        AssetStatistics statistics = tAssetService.getAssetStatistics();
        return success(statistics);
    }

    /**
     * 获取资产维修历史
     */
    @PreAuthorize("@ss.hasPermi('system:asset:query')")
    @GetMapping("/{assetNo}/repairHistory")
    public TableDataInfo getRepairHistory(@PathVariable("assetNo") String assetNo, TAsset tAsset)
    {
        // 这里可以实现维修历史查询逻辑
        // 暂时返回空数据
        startPage();
        return getDataTable(null);
    }

    /**
     * 资产状态更新请求类
     */
    public static class AssetStatusRequest {
        private String assetNo;
        private String statusCode;

        public String getAssetNo() {
            return assetNo;
        }

        public void setAssetNo(String assetNo) {
            this.assetNo = assetNo;
        }

        public String getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(String statusCode) {
            this.statusCode = statusCode;
        }
    }

    /**
     * 验证状态转换是否合理
     */
    private boolean isValidStatusTransition(String currentStatus, String newStatus) {
        if (currentStatus == null || newStatus == null) {
            return true;
        }
        
        // 定义合理的状态转换规则
        if ("ASSET_STATUS_001".equals(currentStatus)) { // 正常 -> 故障、闲置、报废
            return "ASSET_STATUS_002".equals(newStatus) || "ASSET_STATUS_003".equals(newStatus) || "ASSET_STATUS_004".equals(newStatus);
        } else if ("ASSET_STATUS_002".equals(currentStatus)) { // 故障 -> 正常、闲置、报废
            return "ASSET_STATUS_001".equals(newStatus) || "ASSET_STATUS_003".equals(newStatus) || "ASSET_STATUS_004".equals(newStatus);
        } else if ("ASSET_STATUS_003".equals(currentStatus)) { // 闲置 -> 正常、故障、报废
            return "ASSET_STATUS_001".equals(newStatus) || "ASSET_STATUS_002".equals(newStatus) || "ASSET_STATUS_004".equals(newStatus);
        } else if ("ASSET_STATUS_004".equals(currentStatus)) { // 报废 -> 不能转换
            return false;
        }
        
        return true; // 其他情况允许
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(String statusCode) {
        if (statusCode == null) return "未知";
        switch (statusCode) {
            case "ASSET_STATUS_001": return "正常";
            case "ASSET_STATUS_002": return "故障";
            case "ASSET_STATUS_003": return "闲置";
            case "ASSET_STATUS_004": return "报废";
            default: return "未知";
        }
    }

    /**
     * 批量资产状态更新请求类
     */
    public static class BatchAssetStatusRequest {
        private String[] assetNos;
        private String statusCode;

        public String[] getAssetNos() {
            return assetNos;
        }

        public void setAssetNos(String[] assetNos) {
            this.assetNos = assetNos;
        }

        public String getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(String statusCode) {
            this.statusCode = statusCode;
        }
    }
}
